from datetime import datetime
from google.appengine.ext import db
from google.appengine.api import users


class Page(db.Model):
    #text = db.TextProperty(default=u'Blank page')
    name = db.StringProperty()
    viewers = db.ListProperty(users.User)
    ispublic = db.BooleanProperty()

    @property
    def viewers_list(self):
        return ' '.join([user.email() for user in self.viewers])


    @property
    def body(self):
        query = PageTextData.all()
        query.filter('name = ', 'body')
        query.filter('iscurrent = ', True)
        query.ancestor(self)
        return query.fetch(1)[0]

    def update(self, text, viewers):
        timestamp = datetime.utcnow()
        old_body = self.body
        new_text = PageTextData(value=text,
                                       key_name='body|' + str(timestamp),
                                      name='body',
                                      creation_date = timestamp,
                                      derived_from_date = old_body.creation_date,
                                        parent=self)
        if old_body.iscurrent:
            old_body.iscurrent = False
            new_text.iscurrent = True
        else:
            new_text.iscurrent = False
        self.viewers = viewers
        self.ispublic = False if viewers else True
        db.put([new_text,old_body,self])

    @classmethod
    def create(cls,name, text,viewers):

        def save_page():
            new_page = cls(name=name, key_name='-'+name,viewers=viewers,
                           ispublic=False if viewers else True)
            new_page.put()
            timestamp = datetime.utcnow()
            new_text = PageTextData(value=text,
                                          name = 'body',
                                           key_name='body|' + str(timestamp),
                                          creation_date = timestamp,
                                            parent=new_page)
            db.put(new_text)

        db.run_in_transaction(save_page)

    @property
    def id(self):
        return self.key().name()

class PageTextData(db.Model):
    name = db.StringProperty()
    creation_date = db.DateTimeProperty()
    derived_from_date = db.DateTimeProperty()
    value = db.TextProperty()
    iscurrent = db.BooleanProperty(default=True)
